<template>
  <div style="height: 100%">
    <div class="searchBox">
      <form-box
        :fields="searchField"
        :is-filter="true"
        :submit-handle="searchHandle"
      />
    </div>

    <div class="baby-box">
      <div style="display: flex">
        <el-button type="primary" @click="addBaby">添加宝宝</el-button>
        <el-button
          class="btn-primary-box"
          icon="el-icon-download"
          @click="handleDownload"
        >宝宝导入模板</el-button>
        <el-upload
          v-if="classId"
          class="upload-demo ml10"
          :headers="headers"
          :action="action"
          :show-file-list="false"
          accept=".xls,.xlsx"
          :on-change="handleChange"
          :before-upload="beforeUpload"
        >
          <el-button
            icon="el-icon-upload"
            class="btn-primary-box"
          >导入
          </el-button>
        </el-upload>
        <el-button
          v-else
          icon="el-icon-upload"
          class="btn-primary-box"
          @click="beforeUpload"
        >导入
        </el-button>
      </div>
      <!-- <l-table :data="[1]" :config="config.columns" v-if="list.length > 0"></l-table> -->
      <Ltable
        v-if="list.length > 0 || loading"
        :data="list"
        :columns="config.manageColumns"
        class="mt16"
        :loading="loading"
      >
        <template #status="{ row }">
          <div
            style="display: flex; align-items: center; justify-content: center"
          >
            <div
              :class="
                states[row.status != 3 && row.status != 4 ? 1 : row.status][
                  'class'
                ]
              "
              style="margin-right: 6px"
            />
            <span
              :class="
                states[row.status != 3 && row.status != 4 ? 1 : row.status][
                  'spClass'
                ]
              "
            >{{
              states[row.status != 3 && row.status != 4 ? 1 : row.status][
                "span"
              ]
            }}</span>
          </div>
        </template>
        <template #birthday="{ row }">
          {{ date.formatTimestamp(row["birthday"], "date") }}
        </template>
        <template #createTime="{ row }">
          {{ date.formatTimestamp(row["createTime"], "date") }}
        </template>
        <template #operate="{ row }">
          <el-button
            size="mini"
            type="text"
            class="yellow"
            @click="getDetail(row.id, 1)"
          >详情</el-button>
          <el-button
            v-if="[1, 2, 3, 4].includes(row.status)"
            size="mini"
            type="text"
            class="yellow"
            @click="editBaby(row.id)"
          >编辑</el-button>
          <!-- <el-button v-if="[1, 2].includes(row.status)" size="mini" type="text" class="red">休学</el-button> -->
          <!-- <el-button v-if="[2, 3].includes(row.status)" size="mini" type="text" class="blue">入学</el-button> -->
          <el-button
            v-if="[1, 2].includes(row.status)"
            size="mini"
            type="text"
            class="blue"
            @click="
              detail['id'] = row.id;
              dropOutVisible = true;
            "
          >退学</el-button>
          <el-popconfirm
            title="您确认对该名学生进行毕业操作吗?"
            class="ml10"
            @confirm="() => graduateHandle(row.id)"
            @onConfirm="() => graduateHandle(row.id)"
          >
            <el-button
              v-if="[1, 2, 3].includes(row.status)"
              slot="reference"
              size="mini"
              type="text"
              class="green"
            >毕业</el-button>
          </el-popconfirm>
        </template>
      </Ltable>
      <div v-else class="quesheng">
        <img src="@/assets/quesheng.png" alt="">
        <span>暂无数据</span>
      </div>
      <div v-if="list.length > 0 && !loading" style="text-align: right">
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :before-close="beforeClose"
      :destroy-on-close="true"
      custom-class="add-drawer"
      size="45%"
      :wrapper-closable="false"
    >
      <div v-loading="loadingFrom" style="padding: 0 30px">
        <div>
          <div>
            <div
              style="
                font-weight: bold;
                vertical-align: middle;
                font-size: 15px;
                color: #333;
                line-height: 36px;
                padding: 0 12px 0 0;
                box-sizing: border-box;
              "
            >
              <span style="color: #ff4949">*</span> 是否使用优惠券
            </div>
          </div>
          <div style="margin: 10px 0px">
            <el-radio v-model="radio" label="1">是</el-radio>
            <el-radio v-model="radio" label="2">否</el-radio>
          </div>
        </div>
        <div v-if="radio === '1'">
          <div>
            <div
              style="
                font-weight: bold;
                vertical-align: middle;
                font-size: 15px;
                color: #333;
                line-height: 36px;
                padding: 0 12px 0 0;
                box-sizing: border-box;
              "
            >
              <span style="color: #ff4949">*</span> 优惠券码
            </div>
          </div>
          <el-input v-model="inputValue" placeholder="请输入内容" />
        </div>
        <from-page
          ref="fromRef"
          :label-width="null"
          :rules="config.rules"
          :grid-data="gridData"
          :from-config="config.babyFrom"
          :disabled-from="disabledFrom"
          :value="detail"
          @submitForm="submitForm"
        >
          <template #append>
            <div class="mt20 drawer-top">
              <div>家属信息</div>
              <i
                v-if="!disabledFrom"
                class="el-icon-circle-plus-outline"
                @click="contacts.push(null)"
              />
            </div>
            <div
              v-for="(item, index) in contacts"
              :key="index"
              class="drawer-box mt16"
            >
              <div class="drawer-top" style="font-size: 16px">
                <div>联系人</div>
                <i
                  v-if="!disabledFrom"
                  class="el-icon-close"
                  @click="contacts.splice(index, 1)"
                />
              </div>
              <from-page
                :ref="`fromContact${index}`"
                class="mt10"
                :rules="config.contactRules"
                :label-width="null"
                :grid-data="gridData"
                :from-config="config.contactFrom"
                :but-show="false"
                :disabled-from="disabledFrom"
                :value="contacts[index] || {}"
              />
              <div class="mt20 drawer-top" />
            </div>
            <div
              v-if="!config.babyFrom[3]['show']"
              style="
                margin-top: 20px;
                background: #fafafd;
                border: 1px solid #ebebee;
                padding: 16px;
              "
            >
              {{ detail.statusRemark }}
            </div>
          </template>
        </from-page>
      </div>
    </el-drawer>
    <modal-form
      title="退学"
      :visible.sync="dropOutVisible"
      :fields="addField"
      :submit-handle="addSubmit"
      :submitting="addSubmitting"
      :layout-col="{ sm: 24, md: 24, lg: 24 }"
    />
  </div>
</template>

<script>
import * as config from '../config'
import FromPage from '@/components/Basic/FromPage/index'
import { mapGetters } from 'vuex'
import { getClassesByArea } from '@/api/common'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'
import { getChildrenDetail, createChild } from '@/api/common'
import { dropOut, graduate } from '../api'
import * as date from '@/utils/date'
import axios from 'axios'
export default {
  name: 'Manage',
  components: {
    FromPage
  },
  data () {
    return {
      radio: '1',
      inputValue: '',
      date,
      dropOutVisible: false,
      addSubmitting: false,
      detail: {},
      loadingFrom: false,
      disabledFrom: false,
      states: {
        1: {
          class: 'yuan',
          span: '正常'
        },
        3: {
          class: 'yuan redBac',
          span: '退学',
          spClass: 'red'
        },
        4: {
          class: 'yuan greenBac',
          span: '毕业'
        }
      },
      contacts: [],
      title: '添加宝宝',
      gridData: {
        columns: 2, // 默认列数
        rows: 1, // 默认行数
        rowsWidth: '77px',
        columnsNumber: '10px',
        rowsNumber: '10px'
      },
      config,
      action: `${process.env.VUE_APP_BASE_API}/v2/child/importChild`,
      headers: { ticket: getToken() },
      drawer: false,
      total: 1,
      // 查询参数
      queryParams: {
        status: 1,
        pageNum: 1,
        pageSize: 10
      },
      types: [
        {
          id: -1,
          name: '全部'
        },
        {
          id: 1,
          name: '正常'
        },
        {
          id: 2,
          name: '休学'
        },
        {
          id: 3,
          name: '退学'
        },
        {
          id: 4,
          name: '毕业'
        }
      ],
      loading: true,
      list: [],
      classId: '',
      classes: [],
      log: null
    }
  },
  watch: {
    radio (nweValue, oldValue) {
      this.inputValue = ''
    }
  },
  computed: {
    ...mapGetters(['curArea']),
    searchField () {
      const { classId, types } = this
      return [
        {
          key: 'name',
          label: '宝宝姓名'
        },
        {
          key: 'classId',
          label: '班级名称',
          type: 'select',
          initialValue: classId,
          fieldProps: {
            options: this.classes,
            props: { value: 'id', label: 'name' }
          },
          events: {
            change: (val) => this.classChange(val),
            clear: (val) => {
              this.classId = ''
            }
          }
        },
        {
          key: 'status',
          label: '就学状态',
          type: 'select',
          initialValue: this.queryParams.status,
          fieldProps: {
            options: types,
            props: { value: 'id', label: 'name' }
          }
          // events: {
          //     change: val => this.classChange(val)
          // }
        }
      ]
    },
    addField () {
      return [
        {
          key: 'reason',
          label: '退学原因',
          rules: [{ required: true, message: '请输入' }]
        }
      ]
    }
  },
  created () {
    this.getClassList()
  },
  methods: {
    // 退学操作
    addSubmit (values) {
      const { id: childrenId } = this.detail
      const { areaId } = this.curArea
      const { reason } = values

      const params = {
        childrenId,
        areaId,
        reason,
        backMoney: 0
      }
      this.addSubmitting = true
      dropOut(params)
        .then((res) => {
          this.refreshTable()
        })
        .finally(() => {
          this.addSubmitting = false
          this.dropOutVisible = false
        })
    },
    // 毕业操作
    graduateHandle (childrenId) {
      this.loading2()
      const { areaId } = this.curArea
      const params = {
        childrenId,
        areaId
      }
      graduate(params)
        .then((res) => {
          this.$message.success('操作成功')
          this.init()
        })
        .finally(() => {
          this.loadingFrom = false
          this.log && this.log.close()
        })
    },
    beforeClose () {
      this.$refs.fromRef.resetFields()
      this.drawer = false
    },
    // 宝宝添加/修改操作
    async submitForm (e) {
      if (this.radio === '1' && this.inputValue === '') {
        this.$message.info('请输入优惠券码')
        return
      }
      if (this.contacts.length <= 0) {
        this.$message.info('请至少添加一位联系人')
        return
      }
      const list = []
      for (let i = 0; i < this.contacts.length; i++) {
        const fromContact = await this.$refs['fromContact' + i][0].submitForm()
        const jtdz = fromContact.jtdz
        if (jtdz?.province?.code) {
          fromContact['province'] = jtdz.province.value
          fromContact['city'] = jtdz.city.value
          fromContact['district'] = jtdz.area.value
        }
        delete fromContact['area']
        delete fromContact['jtdz']
        list.push({ ...fromContact })
      }
      e['birthday'] = e['birthday'].replace(/-/g, '/')
      delete e['province']
      delete e['city']
      delete e['area']
      const params = {
        ...e,
        linkMans: [...list]
      }
      if (this.detail['id']) {
        params.childrenId = this.detail['id']
      }
      this.loadingFrom = true
      params.couponCard = this.inputValue
      // 优惠券码字段在这里加
      createChild(params)
        .then((res) => {
          if (res) {
            this.$message.success('保存成功')
            this.beforeClose()
            this.init()
          }
        })
        .finally(() => {
          this.loadingFrom = false
        })
    },
    beforeUpload () {
      if (!this.classId) {
        this.$message.error('请选择班级')
        return false
      } else {
        this.loading2()
      }
    },
    handleChange (file, fileList) {
      if (file['response']) {
        const msg = file['response'].msg
        const code = file['response'].code
        if (code === '999998' || code === '10000005') {
          this.$message.error(msg)
          this.log && this.log.close()
        } else {
          this.init()
          this.$message.success('导入成功')
          this.log && this.log.close()
        }
      }
    },
    // 加载动画
    loading2 (text = '请稍后...') {
      this.log = this.$loading({
        lock: true,
        text,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    /** 编辑按钮操作 */
    handleEdit () {
      this.title = '编辑宝宝'
      this.drawer = true
      this.detail = {}
    },
    /** 下载模板按钮操作 */
    handleDownload () {
      axios
        .get('/api/v2/child/ChildrenMemorandumPageImportTemplate')
        .then((response) => {
          window.open(response.data.data, '_blank')
        })
    },
    init () {
      this.queryParams.pageNum = 1
      this.list = []
      this.getList()
    },
    searchHandle (res) {
      if (!res.classId && res.name) {
        this.$message.error('请选择班级')
        return
      }
      this.queryParams.pageNum = 1
      this.list = []
      this.queryParams = { ...this.queryParams, ...res }
      this.getList()
    },
    addBaby () {
      // if (!this.classId) {
      //   this.$message.error('请选择班级')
      //   return
      // }
      this.inputValue = ''
      this.config.babyFrom[3]['show'] = true
      this.title = '添加宝宝'
      this.drawer = true
      this.disabledFrom = false
    },
    async editBaby (childrenId) {
      this.inputValue = ''
      this.config.babyFrom[3]['show'] = true
      this.loading2()
      this.title = '编辑宝宝'
      await this.getDetail(childrenId)
      this.disabledFrom = false
    },
    getDetail (childrenId, type) {
      if (type) {
        this.config.babyFrom[3]['show'] = false
      }
      this.disabledFrom = true
      getChildrenDetail({ childrenId })
        .then((res) => {
          this.detail = res?.children
          this.inputValue = this.detail.couponCard
          console.log(this.detail, 'this.inputValue')
          this.detail['birthday'] = date.formatTimestamp(
            this.detail['birthday']
          )
          this.detail['gender'] = this.detail['gender'] + ''
          this.contacts = res?.users
          this.$nextTick(() => {
            this.drawer = true
          })
        })
        .finally(() => {
          this.log && this.log.close()
        })
    },
    getList () {
      const { curArea } = this
      const queryParams = JSON.parse(JSON.stringify(this.queryParams))
      queryParams.pageNum--
      this.loading = true
      console.log(queryParams)
      request({
        url: 'web/children/page',
        method: 'post',
        params: { areaId: curArea.areaId, ...queryParams }
      }).then((res) => {
        this.loading = false
        this.list = res.content
        this.total = res.totalElements
      })
    },
    // 获取班级列表
    getClassList () {
      const { curArea } = this
      getClassesByArea({ areaId: curArea.areaId, category: 1 }).then((res) => {
        this.classes = res || []
        // 默认查询全部
        // this.classChange(this.classes[0] ? this.classes[0].id : '')
        this.queryParams.classId = this.classId
        this.getList()
      })
    },
    // 选择班级
    classChange (val) {
      this.classId = val
    }
  }
}
</script>

<style lang="scss" scope>
.drawer-box {
  padding: 16px;
  background: #fafafd;
  border-radius: 4px;
  border: 1px solid #ebebee;
}

.drawer-top {
  display: flex;
  justify-content: space-between;
  align-items: center;

  div {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 500;
    text-align: left;
    font-style: normal;
    text-transform: none;
    font-size: 18px;
  }
}

.baby-box .pagination-container {
  margin-top: 0px;
}

.baby-box {
  margin-top: 16px;
  background-color: #ffffff;
  border-radius: 8px;
  padding: 24px;
  overflow: auto;
  height: calc(100% - 100px);
}

.baby-box {
  th.is-leaf {
    height: 66px;
  }

  th {
    color: #000;
    font-size: 17px;
    background: #fafafa;
    font-family: PingFang SC;
    font-weight: bold;
  }

  td {
    padding: 20px 0;
  }
}

.quesheng {
  padding-top: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: 100%;

  span {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 400;
    font-size: 16px;
    color: #333333;
    font-style: normal;
    text-transform: none;
    margin-top: 32px;
  }
}

.searchBox .el-form-item {
  margin-bottom: 0 !important;
}

.baby-box .el-table--border {
  border: 0;
}

.searchBox {
  background: #ffffff;
  border-radius: 8px;
  padding: 16px 20px;
}

.hint {
  margin-top: 10px;
}

.weekend-bg {
  background: #7d7d7f;
  width: 100%;
  height: 100%;
}

.el-table {
  .cell {
    padding: 0;
  }
}

.el-table {
  th {
    .cell {
      padding: 0;
    }
  }
}
</style>
